package com.fmjava.service.Impl;


import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadFileStreamRequest;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadFileStreamResponse;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.fmjava.config.VodAppConfig;
import com.fmjava.service.VodService;
import com.fmjava.utils.AliyunVodSDKUtils;
import com.fmjava.service_base.exception.MyException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/*
 *@ClassName VodServiceImpl
 *@Description TODO
 *@Author 吃麻椒的花酱
 *@Date 2021/8/18 12:25
 *@Version 1.0
 */
@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadVod(MultipartFile file) {

        try {
            //文件名
            String originalFilename = file.getOriginalFilename();
            String title = originalFilename.substring(0, originalFilename.indexOf("."));
            UploadStreamRequest request = new UploadStreamRequest(VodAppConfig.ACCESS_KEY_ID, VodAppConfig.ACCESS_KEY_SECRET, title, originalFilename,file.getInputStream());
            /* 点播服务接入点 */
            //request.setApiRegionId("cn-shanghai");
            /* ECS部署区域*/
            //request.setEcsRegionId("cn-shanghai");
            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            //上传视频的ID
            String videoId = response.getVideoId();
            if (!response.isSuccess()) {
                System.out.println("上传失败，状态码：" + response.getCode() + ",错误信息：" + response.getMessage());

                if (StringUtils.isEmpty(videoId)) {
                    throw new MyException(20001, "上传失败");
                }
            }

            return videoId;

        } catch (IOException e) {
            e.printStackTrace();
            throw new MyException(20001, "上传失败");
        }

    }


    @Override
    public void deleteVod(String vodId) {

        try {
            DefaultAcsClient defaultAcsClient = AliyunVodSDKUtils.initClient(VodAppConfig.ACCESS_KEY_ID, VodAppConfig.ACCESS_KEY_SECRET);
            //删除请求
            DeleteVideoRequest request = new DeleteVideoRequest();
            request.setVideoIds(vodId);
            //删除响应
            DeleteVideoResponse acsResponse = defaultAcsClient.getAcsResponse(request);

        } catch (ClientException e) {
            throw  new MyException(20001, "删除失败");
        }


    }
}
